package com.lyj.io.module.sys.controller;

import com.lyj.io.annotation.SysLogAnnotation;
import com.lyj.io.common.utils.R;
import com.lyj.io.module.sys.dto.JasyptDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 加密相关api
 * @author:liyajie
 * @createTime:2021/12/26 23:33
 * @version:1.0
 */
@Api(value = "JasyptController", tags = "加密相关api")
@RestController
@RequestMapping("/api/v1/jasypt")
public class JasyptController {

    @Autowired
    StringEncryptor encryptor;

    /*
     * 加密
     * @author: liyajie
     * @date: 2021/12/26 23:38
     * @param
     * @return com.lyj.io.common.utils.R
     * @exception:
     * @update:
     * @updatePerson:
     **/
    @SysLogAnnotation("加密")
    @ApiOperation(value = "加密", notes = "加密")
    @PostMapping("/encrypt")
    public R encrypt(@RequestBody JasyptDto jasyptDto){
        Map<String, String> map = new HashMap<String, String>();
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        //加密所需的salt(盐)
        textEncryptor.setPassword(jasyptDto.getSalt());
        map.put("username",textEncryptor.encrypt(jasyptDto.getUsername()));
        map.put("password",textEncryptor.encrypt(jasyptDto.getPassword()));
        return R.ok().put("data", map);
    }

    /*
     * 解密
     * @author: liyajie
     * @date: 2021/12/26 23:38
     * @param
     * @return com.lyj.io.common.utils.R
     * @exception:
     * @update:
     * @updatePerson:
     **/
    @SysLogAnnotation("解密")
    @ApiOperation(value = "解密", notes = "解密")
    @PostMapping("/decrypt")
    public R decrypt(@RequestBody JasyptDto jasyptDto){
        Map<String, String> map = new HashMap<String, String>();
        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        //加密所需的salt(盐)
        textEncryptor.setPassword(jasyptDto.getSalt());
        map.put("username",textEncryptor.decrypt(jasyptDto.getUsername()));
        map.put("password",textEncryptor.decrypt(jasyptDto.getPassword()));
        return R.ok().put("data", map);
    }
}
